package com.example.demotest.service;

import com.example.demotest.pojo.Address;
import com.example.demotest.pojo.Admin;
import com.example.demotest.pojo.dto.AddressDto;
import com.example.demotest.repository.AddressRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class AddressService implements IAddressService{

    @Autowired
    private AddressRepository addressRepository;

    @Override
    public List<AddressDto> getAllAddresses(Integer userId) {
        List<Address> addresses = addressRepository.findByUserId(userId);
        return addresses.stream().map(this::toDto).collect(Collectors.toList());
    }

    @Override
    public AddressDto addAddress(AddressDto dto) {
        Address address = toEntity(dto);
        Address saved = addressRepository.save(address);

        // 如果设置为默认地址，清除其他默认地址
        if (Boolean.TRUE.equals(dto.getDefaultFlag())) {
            addressRepository.clearOtherDefaultFlags(saved.getUserId(), saved.getId());
        }

        return toDto(saved);
    }

    @Override
    public boolean isDuplicateAddress(AddressDto dto) {
        List<Address> existing = addressRepository.findByUserId(dto.getUserId());

        for (Address addr : existing) {
            if (
                    addr.getConsigneeName().equals(dto.getConsigneeName()) &&
                            addr.getConsigneePhone().equals(dto.getConsigneePhone()) &&
                            addr.getProvinceName().equals(dto.getProvinceName()) &&
                            addr.getCityName().equals(dto.getCityName()) &&
                            addr.getRegionName().equals(dto.getRegionName()) &&
                            addr.getDetailAddress().equals(dto.getDetailAddress()) &&
                            addr.getDefaultFlag() == dto.getDefaultFlag()
            ) {
                return true;
            }
        }
        return false;
    }

    @Transactional
    @Override
    public AddressDto updateAddress(AddressDto dto) {
        if (dto.getId() == null) {
            throw new RuntimeException("缺少地址ID，无法更新");
        }

        Address address = addressRepository.findById(dto.getId())
                .orElseThrow(() -> new RuntimeException("地址不存在"));

        if (!address.getUserId().equals(dto.getUserId())) {
            throw new RuntimeException("无权限修改该地址");
        }

        // 如果设置为默认地址，清除其他默认地址
        if (Boolean.TRUE.equals(dto.getDefaultFlag())) {
            addressRepository.clearOtherDefaultFlags(dto.getUserId(), dto.getId());
        }

        // 更新当前地址信息（除 id、userId 外）
        BeanUtils.copyProperties(dto, address, "id", "userId");
        Address updated = addressRepository.save(address);

        return toDto(updated);
    }


    @Override
    public void deleteAddress(Integer userId, Integer addressId) {
        Address address = addressRepository.findById(addressId)
                .orElseThrow(() -> new RuntimeException("地址不存在"));
        if (!address.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除该地址");
        }
        addressRepository.deleteById(addressId);
    }

    @Override
    public int countByUserId(Integer userId) {
        return addressRepository.countByUserId(userId);
    }

    // DTO ↔ Entity 转换方法
    private AddressDto toDto(Address entity) {
        AddressDto dto = new AddressDto();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    private Address toEntity(AddressDto dto) {
        Address entity = new Address();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
}
